package com.xhh.hybriddemo.common;

import android.app.Activity;
import android.app.Application;
import android.content.pm.ApplicationInfo;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.util.Log;


import com.squareup.leakcanary.LeakCanary;
import com.squareup.leakcanary.RefWatcher;
import com.xhh.hybriddemo.ui.activity.MainActivity;
import com.xhh.hybriddemo.utils.DensityUtils;
import com.xhh.hybriddemo.utils.PreferenceUtil;

import java.io.IOException;
import java.lang.ref.WeakReference;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.Stack;
import java.util.zip.ZipEntry;
import java.util.zip.ZipFile;

/**
 * 应用上下文
 */
public class AppContext extends Application {

    // 应用上下文
    private static AppContext mAppContext;

    // 渠道
    private static String channel;

    // 包信息
    private static PackageInfo mPackageInfo;

    private Map<Class<?>, Activity> mActivitys = new HashMap<>();
    private Stack<WeakReference<Activity>> mActivityStack;

  //  private RefWatcher mRefWatcher;
    @Override
    public void onCreate() {
        super.onCreate();
        mAppContext = this;
        // 初始化异常处理
        AppExceptionHandler.getInstance().init(mAppContext);
        PreferenceUtil.getInstance().init(mAppContext);//SharedPreferences
        DensityUtils.init(mAppContext);
      //  mRefWatcher =  LeakCanary.install(this);

    }


    // 获取上下文
    public static AppContext getInstance() {
        return mAppContext;
    }

    // 获取当前包渠道名称
    public synchronized static String getChannelName() {
        if (channel != null) {
            return channel;
        }
        ApplicationInfo appinfo = mAppContext.getApplicationInfo();
        String sourceDir = appinfo.sourceDir;
        String ret = "";
        ZipFile zipfile = null;
        try {
            zipfile = new ZipFile(sourceDir);
            Enumeration<?> entries = zipfile.entries();
            while (entries.hasMoreElements()) {
                ZipEntry entry = ((ZipEntry) entries.nextElement());
                String entryName = entry.getName();
                if (entryName.startsWith("META-INF/channel")) {
                    ret = entryName;
                    break;
                }
            }
        } catch (IOException e) {
            Log.w("获取渠道错误", e);
        } finally {
            if (zipfile != null) {
                try {
                    zipfile.close();
                } catch (IOException e) {
                }
            }
        }
        String[] split = ret.split("_");
        if (split != null && split.length >= 2) {
            channel = ret.substring(split[0].length() + 1);
        } else {
            channel = "default";
        }
        return channel;
    }

    // 获取版本名
    public static String getVersionName() {
        PackageInfo packageInfo = getPackageInfo();
        if (packageInfo != null) {
            return getPackageInfo().versionName;
        } else {
            return "null";
        }
    }

    /**
     * 获取版本号
     */
    public static int getVersionCode() {
        PackageInfo packageInfo = getPackageInfo();
        if (packageInfo != null) {
            return getPackageInfo().versionCode;
        } else {
            return -1;
        }
    }

    /**
     * 获取包信息
     */
    private synchronized static PackageInfo getPackageInfo() {
        if (mPackageInfo != null) {
            return mPackageInfo;
        }
        try {
            PackageManager pm = mAppContext.getPackageManager();
            mPackageInfo = pm.getPackageInfo(mAppContext.getPackageName(),
                    PackageManager.GET_CONFIGURATIONS);
        } catch (Exception e) {
            Log.w("获取包信息错误", e);
        }
        return mPackageInfo;
    }

    //添加activity到map中
    public void addActivity(Class<?> activityClass, Activity activity) {
        if (mActivitys.get(activityClass) != null) {
            removeActivity(activityClass);
        }
        mActivitys.put(activityClass, activity);
    }

    public void removeActivity(Class<?> activityClass) {
        Activity activity = mActivitys.get(activityClass);
        if (activity != null) {
            activity.finish();
        }
        mActivitys.remove(activityClass);
    }

    public void exit() {
        Iterator iter = mActivitys.entrySet().iterator();
        while (iter.hasNext()) {
            Map.Entry entry = (Map.Entry) iter.next();
            Activity activity = (Activity) entry.getValue();
            if (activity != null) {
                activity.finish();
            }
        }
    }

    //关闭除了MainActivity之外的activity
    public void removeOtherActivity() {
        Iterator iter = mActivitys.entrySet().iterator();
        while (iter.hasNext()) {
            Map.Entry entry = (Map.Entry) iter.next();
            Activity activity = (Activity) entry.getValue();
            if (activity != null) {
                if (activity instanceof MainActivity) {
                } else {
                    activity.finish();
                }
            }
        }
    }


    /**
     * 添加Activity到栈
     * @param activity
     */
    public void addActivity(Activity activity) {
        if (mActivityStack == null) {
            mActivityStack = new Stack<>();
        }
        mActivityStack.add(new WeakReference<>(activity));
    }

    /**
     * 关闭指定的Activity
     * @param activity
     */
    public void finishActivity(Activity activity) {
        if (activity != null && mActivityStack != null) {
            // 使用迭代器进行安全删除
            for (Iterator<WeakReference<Activity>> it = mActivityStack.iterator(); it.hasNext(); ) {
                WeakReference<Activity> activityReference = it.next();
                Activity temp = activityReference.get();
                // 清理掉已经释放的activity
                if (temp == null) {
                    it.remove();
                    continue;
                }
                if (temp == activity) {
                    it.remove();
                }
            }
            activity.finish();
        }
    }

}
